function varargout = prfft(varargin)

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @prfft_OpeningFcn, ...
                   'gui_OutputFcn',  @prfft_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before prfft is made visible.
function prfft_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to prfft (see VARARGIN)

% Choose default command line output for prfft
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes prfft wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = prfft_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

function psnr(hObject, eventdata, handles)
imagen=double(handles.BW1);
marcada=double(handles.BW2);
d = mean(mean((marcada(:)-imagen(:)).^2));
m1 = max( abs(marcada(:)));
m2 = max( abs(imagen(:)));
m = max(m1,m2);
p = 10*log10(m^2/d);
set(handles.txtpsnr,'String',num2str(p));
guidata(hObject, handles);

% --- Executes on button press in cmdmarcar.
function cmdmarcar_Callback(hObject, eventdata, handles)
   key = str2double(get(handles.txtkey,'String'));
   alfa =str2double(get(handles.txtalfa,'String'));
   I = double(handles.BW1);
   img=double(I)/256;
  
   %I=double(imread('lena.jpg'));
  
   [F,C]=size(I);
  
   Num=str2num(get(handles.txtnum,'String'));  %Mensaje
   bin=dec2bin(Num,12);
   
   Mci=[];
   for i=1:length(bin)
       if(bin(i)=='1')
           Mci=[Mci '11111'];
       else
           Mci=[Mci '00000'];
       end
       
   end
   set(handles.msnO,'String',num2str(bin));
   
   Lc=length(Mci);     %tamaño del mensaje
   
   M=64;
   N=360;
%******* % 1) Watermark Formation  ***************************************
   
   
   Np=64;     %Tamaño de la secuencia bipolar
   PN=zeros(1,Np);

   NT=(M/2)*(N/2)-(Lc*Np);   %longitud del tracking sequence
   RandStream.setDefaultStream(RandStream('mt19937ar','seed',key));
   T=-1+ (1-(-1)).*rand(1,NT);    %Tracking sequence
   
   T(T<=0)=-1;
   T(T>0)=1;
    
   for j=1:2:Np     % Genera PN-sequence.
       n=rand(1);
       if(n<=0.5)
           PN(j)=-1;
           PN(j+1)=1;
       else
           PN(j)=1;     % 1 -1 -1 1 1  -1
           PN(j+1)=-1;
       end
       
   end 
   WM=[];
   for j=1:Lc  %multiplicacion del mensage por la cadena PN.
           if(Mci(j)=='0')
              WM =[WM (-1*PN)];
           else
              WM =[WM PN];
           end
   end
     
   
   
   
   %T=[WM T];
    T=[T WM];
   
  % T=[T(1:1408) WM T(1409:1920)]; %pero deja 512 bits
  
   W1=reshape(T,M/2,N/2);
   W=upsampled(W1);
   
 %********* 2) Applying ULPM to the Frequency Index  ***********
   
   [x,y] = meshgrid(1:F,1:C);
   Ri = I.*((-1).^(x+y));
   
   Im=fft2(Ri); 
   
   axes(handles.marcada); cla;
   imshow(log(abs(Im)),[]);
  
   axes(handles.original); cla;
   imshow(I,[]);
    
   [mar cp]=marcar(Im,W,alfa);
   mar
   axes(handles.fft); cla;
   imshow(mar,[]);
      
   phase = atan2(imag(Im),real(Im));
   I2=(cp.*exp(1j*phase));
   I3=real(ifft2(I2));
   I4 = (I3.*((-1).^(x+y)));
   
   Min = min(I4(:));
   Max = max(I4(:));
   Imarcada = uint8(((I4 - Min) / (Max - Min))*255);
   
   axes(handles.marcada); cla;
   imshow(Imarcada,[]);
   
   handles.BW1 =uint8(I);
   handles.BW2 =uint8(Imarcada);
   handles.op=1;
   handles.sec=PN;
   set(handles.txtpsnr,'String',num2str(abs(psnr1(I,Imarcada))));
  
guidata(hObject, handles);  
   
% hObject    handle to cmdmarcar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

function txtpsnr_Callback(hObject, eventdata, handles)
% hObject    handle to txtpsnr (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtpsnr as text
%        str2double(get(hObject,'String')) returns contents of txtpsnr as a double


% --- Executes during object creation, after setting all properties.
function txtpsnr_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtpsnr (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --------------------------------------------------------------------
function mnuimagen_Callback(hObject, eventdata, handles)
% hObject    handle to mnuimagen (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function mnuabrir_Callback(hObject, eventdata, handles)
[filename pathname filterindex] = uigetfile('*.tif;*.bmp;*.jpg','Selecciona una imagen BMP');
if filterindex == 0
    return;
end
%set(handles.SyP,'Enable','on');
BW1 = imread([pathname filename]);
axes(handles.original); cla;
imshow(BW1);
%axes(handles.marcada); cla;
%imshow(BW1);
%axes(handles.histograma);cla;
%imhist(BW1);
handles.BW1 =uint8(BW1);
%handles.BW2 =uint8(BW1);
guidata(hObject, handles);
% hObject    handle to mnuabrir (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function mnuguardad_Callback(hObject, eventdata, handles)
% hObject    handle to mnuguardad (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function mnusalir_Callback(hObject, eventdata, handles)
close;
% hObject    handle to mnusalir (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)



function txtkey_Callback(hObject, eventdata, handles)
% hObject    handle to txtkey (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtkey as text
%        str2double(get(hObject,'String')) returns contents of txtkey as a double


% --- Executes during object creation, after setting all properties.
function txtkey_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtkey (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function txtalfa_Callback(hObject, eventdata, handles)
% hObject    handle to txtalfa (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtalfa as text
%        str2double(get(hObject,'String')) returns contents of txtalfa as a double


% --- Executes during object creation, after setting all properties.
function txtalfa_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtalfa (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --------------------------------------------------------------------
function mnueditar_Callback(hObject, eventdata, handles)
% hObject    handle to mnueditar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function mnurecortar_Callback(hObject, eventdata, handles)
   
   BW2=handles.BW2;
   axes(handles.marcada); cla;
   imshow(uint8(BW2));
   p=ginput(2);
   sp(1) = min(floor(p(1)), floor(p(2))); %xmin
   sp(2) = min(floor(p(3)), floor(p(4))); %ymin
   sp(3) = max(ceil(p(1)), ceil(p(2)));   %xmax
   sp(4) = max(ceil(p(3)), ceil(p(4)));   %ymax
   cortada=BW2;
   cortada(sp(2):sp(4),sp(1):sp(3))=0;
   axes(handles.marcada); cla;
   imshow(uint8(cortada));
   handles.BW2 =uint8(cortada);
   handles.op=2;
guidata(hObject, handles);
% hObject    handle to mnurecortar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --------------------------------------------------------------------
function mnugirar_Callback(hObject, eventdata, handles)
Mensaje = {'Grados:'};
Titulo = 'Girar';
def = {'90'};
Resp = inputdlg(Mensaje,Titulo,1,def);
if isempty(Resp)
   return;
end
[G E1] = str2num(Resp{1});
Imarcada=handles.BW2;
girada = imrotate(Imarcada,G,'bilinear','crop');

axes(handles.marcada); cla;
imshow(uint8(girada));
handles.BW2 =uint8(girada);
handles.op=3;
guidata(hObject, handles);

% hObject    handle to mnugirar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

function rmin_Callback(hObject, eventdata, handles)
% hObject    handle to rmin (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of rmin as text
%        str2double(get(hObject,'String')) returns contents of rmin as a double

% --- Executes during object creation, after setting all properties.
function rmin_CreateFcn(hObject, eventdata, handles)
% hObject    handle to rmin (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function rmax_Callback(hObject, eventdata, handles)
% hObject    handle to rmax (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of rmax as text
%        str2double(get(hObject,'String')) returns contents of rmax as a double


% --- Executes during object creation, after setting all properties.
function rmax_CreateFcn(hObject, eventdata, handles)
% hObject    handle to rmax (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
close;
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% --- Executes on button press in btndetectar.

function btndetectar_Callback(hObject, eventdata, handles)
 
 op=handles.op;

 %Imarcada=double(imread('marca_50.jpg'));
 %op=1;
 
  Imarcada=double(handles.BW2);
 
 [Fu Cf M Mayor]=corr3(Imarcada);
 
 F=downsampled(Fu);
 Np1=handles.sec;
 
 [NM fil col]=MatrixMax(Fu);
 A=reshape(F,1,5760);
 [a Ma]=max(max(Cf));
 %Ma=((fil-1)*360+col);
 %Ma=2+1792+128-Ma;
 Ma=((floor(Ma-1)/2)*32)+1;
 A1=[A(Ma:5760) A(1:Ma-1)];

 Ma=1;
 msn=[];
 
 for i=1:90
    F1=A1(Ma:Ma+63);
    Np=mapminmax(F1); 
    v=correlacion(Np1,Np);
    if(v>0)
       msn=[msn '1'];
    else
       msn=[msn '0'];
    end
    Ma=Ma+64;
 end
 
 cad=[]
 for i=31:5:90
    subcad=(msn(i:i+4));
    unos=length(subcad(subcad(:)=='1')); 
    ceros=length(subcad(subcad(:)=='0')); 
    if(unos>ceros)
        cad=[cad '1'];
    else
        cad=[cad '0'];
    end
 end
 
 set(handles.lblnum,'String',num2str(bin2dec(cad)));
 set(handles.msnR,'String',cad);
 
 Min = min(Cf(:));
 Max = max(Cf(:));
 Im= uint8(((Cf - Min) / (Max - Min))*255);
 axes(handles.fft); cla;
 imshow(Im);
 
 
 %figure; subplot(1,1,1);
 %bar3(Im);
 %[A B]=max(max(Im));
 
 
 axes(handles.grafica); %hold on; cla; 
 axis([0,100,-50,50]);
 switch op
     case 1
         set(handles.lblmax1,'String',Mayor);
         plot(M, 'r','LineWidth', 2);
     case 2
         set(handles.lblmax2,'String',Mayor);
         plot(M, 'g','LineWidth', 2);
     case 3
         set(handles.lblmax3,'String',Mayor);
         plot(M, 'y','LineWidth', 2);
 end
 
 handles.BW2=uint8(Imarcada); 
guidata(hObject, handles);


% --- Executes on button press in btnabrir.
function btnabrir_Callback(hObject, eventdata, handles)
[filename pathname filterindex] = uigetfile('*.tif;*.bmp;*.jpg','Selecciona una imagen BMP');
if filterindex == 0
    return;
end

BW1 = imread([pathname filename]);
axes(handles.original); cla;
imshow(BW1);
handles.BW1 =uint8(BW1);
handles.BW2 =BW1;
guidata(hObject, handles);
% hObject    handle to btnabrir (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in btnguardar.
function btnguardar_Callback(hObject, eventdata, handles)
BW2=handles.BW2;
if isempty(BW2), return, end
formatos={'*.tif','TIFF (*.tif)'; '*.png','PNG (*.PNG)'; '*.jpg','jpg (*.jpg)'; '*.bmp','BMP (*.bmp)'; };
[nombre, ruta]= uiputfile(formatos,'Guardar Imagen');
if(nombre==0), return, end
fName=fullfile(ruta,nombre);
imwrite(BW2,fName);
guidata(hObject,handles);

    
% hObject    handle to btnguardar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in cmdrecortar.
function cmdrecortar_Callback(hObject, eventdata, handles)
   BW2=handles.BW2;
   axes(handles.marcada); cla;
   imshow(uint8(BW2));
   p=ginput(2);
   sp(1) = min(floor(p(1)), floor(p(2))); %xmin
   sp(2) = min(floor(p(3)), floor(p(4))); %ymin
   sp(3) = max(ceil(p(1)), ceil(p(2)));   %xmax
   sp(4) = max(ceil(p(3)), ceil(p(4)));   %ymax
   cortada=BW2;
   cortada(sp(2):sp(4),sp(1):sp(3))=0;
   axes(handles.marcada); cla;
   imshow(uint8(cortada));
   handles.BW2 =uint8(cortada);
   handles.op=2;
guidata(hObject, handles);

% hObject    handle to cmdrecortar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in cmdgirar.
function cmdgirar_Callback(hObject, eventdata, handles)
Mensaje = {'Grados:'};
Titulo = 'Girar';
def = {'90'};
Resp = inputdlg(Mensaje,Titulo,1,def);
if isempty(Resp)
   return;
end
[G E1] = str2num(Resp{1});
Imarcada=handles.BW2;
girada = imrotate(Imarcada,G,'bicubic','crop');

axes(handles.marcada); cla;
imshow(uint8(girada));
handles.BW2 =uint8(girada);
handles.op=3;
guidata(hObject, handles);

% hObject    handle to cmdgirar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

function msnO_Callback(hObject, eventdata, handles)
% hObject    handle to msnO (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of msnO as text
%        str2double(get(hObject,'String')) returns contents of msnO as a double


% --- Executes during object creation, after setting all properties.
function msnO_CreateFcn(hObject, eventdata, handles)
% hObject    handle to msnO (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function msnR_Callback(hObject, eventdata, handles)
% hObject    handle to msnR (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of msnR as text
%        str2double(get(hObject,'String')) returns contents of msnR as a double

% --- Executes during object creation, after setting all properties.
function msnR_CreateFcn(hObject, eventdata, handles)
% hObject    handle to msnR (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function txtnum_Callback(hObject, eventdata, handles)
% hObject    handle to txtnum (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtnum as text
%        str2double(get(hObject,'String')) returns contents of txtnum as a double


% --- Executes during object creation, after setting all properties.
function txtnum_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtnum (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
